/**
 * 调试工具集，用于检测和防止无限刷新循环
 */

// 页面刷新计数器键名
const REFRESH_COUNTER_KEY = 'page-refresh-counter';
const REFRESH_HISTORY_KEY = 'page-refresh-history';

/**
 * 检测页面刷新频率
 * @param maxRefreshes 最大刷新次数
 * @param timeWindow 时间窗口（毫秒）
 * @returns 如果检测到异常刷新频率则返回true
 */
export const detectRefreshLoop = (maxRefreshes: number = 5, timeWindow: number = 10000): boolean => {
  try {
    const history = getRefreshHistory();
    const now = Date.now();
    
    // 过滤出时间窗口内的记录
    const recentRefreshes = history.filter(timestamp => now - timestamp < timeWindow);
    
    // 如果在时间窗口内刷新次数超过阈值，认为是异常
    if (recentRefreshes.length >= maxRefreshes) {
      console.warn(`检测到异常刷新频率: ${recentRefreshes.length}次刷新在${timeWindow/1000}秒内`);
      return true;
    }
    
    // 记录本次刷新
    recordRefresh();
    return false;
  } catch (error) {
    console.error('检测刷新循环时出错:', error);
    return false;
  }
};

/**
 * 获取刷新历史记录
 */
export const getRefreshHistory = (): number[] => {
  try {
    const historyStr = sessionStorage.getItem(REFRESH_HISTORY_KEY);
    return historyStr ? JSON.parse(historyStr) : [];
  } catch (error) {
    console.error('获取刷新历史记录时出错:', error);
    return [];
  }
};

/**
 * 记录页面刷新
 */
export const recordRefresh = (): void => {
  try {
    const history = getRefreshHistory();
    const now = Date.now();
    
    // 只保留最近20条记录
    const updatedHistory = [...history.slice(-19), now];
    sessionStorage.setItem(REFRESH_HISTORY_KEY, JSON.stringify(updatedHistory));
  } catch (error) {
    console.error('记录刷新时出错:', error);
  }
};

/**
 * 清除刷新历史记录
 */
export const clearRefreshHistory = (): void => {
  try {
    sessionStorage.removeItem(REFRESH_HISTORY_KEY);
    console.log('刷新历史记录已清除');
  } catch (error) {
    console.error('清除刷新历史记录时出错:', error);
  }
};

/**
 * 获取页面刷新计数
 */
export const getRefreshCount = (): number => {
  try {
    const countStr = sessionStorage.getItem(REFRESH_COUNTER_KEY);
    return countStr ? parseInt(countStr, 10) : 0;
  } catch (error) {
    console.error('获取刷新计数时出错:', error);
    return 0;
  }
};

/**
 * 增加页面刷新计数
 */
export const incrementRefreshCount = (): number => {
  try {
    const currentCount = getRefreshCount();
    const newCount = currentCount + 1;
    sessionStorage.setItem(REFRESH_COUNTER_KEY, newCount.toString());
    return newCount;
  } catch (error) {
    console.error('增加刷新计数时出错:', error);
    return 0;
  }
};

/**
 * 重置页面刷新计数
 */
export const resetRefreshCount = (): void => {
  try {
    sessionStorage.removeItem(REFRESH_COUNTER_KEY);
    console.log('刷新计数已重置');
  } catch (error) {
    console.error('重置刷新计数时出错:', error);
  }
};

/**
 * 检测并处理刷新循环
 * @param maxRefreshes 最大刷新次数
 * @param timeWindow 时间窗口（毫秒）
 * @returns 如果检测到并处理了刷新循环则返回true
 */
export const handleRefreshLoop = (maxRefreshes: number = 5, timeWindow: number = 10000): boolean => {
  // 增加刷新计数
  const refreshCount = incrementRefreshCount();
  
  // 检测刷新循环
  if (detectRefreshLoop(maxRefreshes, timeWindow)) {
    console.warn('检测到页面刷新循环，正在采取措施...');
    
    // 显示警告信息
    showRefreshLoopWarning();
    
    // 可以选择清除某些缓存来尝试解决问题
    clearTroublesomeCache();
    
    return true;
  }
  
  // 如果刷新次数过多，也显示警告
  if (refreshCount > 20) {
    console.warn(`页面已刷新${refreshCount}次，可能存在异常`);
    showHighRefreshWarning(refreshCount);
  }
  
  return false;
};

/**
 * 显示刷新循环警告
 */
const showRefreshLoopWarning = (): void => {
  // 在页面上显示警告信息
  const warningDiv = document.createElement('div');
  warningDiv.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background: #ff4d4f;
    color: white;
    padding: 10px;
    text-align: center;
    z-index: 9999;
    font-size: 14px;
  `;
  warningDiv.innerHTML = `
    ⚠️ 检测到页面刷新异常，系统正在自动处理...
    <button onclick="location.reload()" style="margin-left: 10px; background: white; color: #ff4d4f; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;">
      手动刷新
    </button>
  `;
  document.body.insertBefore(warningDiv, document.body.firstChild);
};

/**
 * 显示高刷新次数警告
 * @param count 刷新次数
 */
const showHighRefreshWarning = (count: number): void => {
  console.warn(`页面刷新次数过多: ${count}次`);
  
  // 可以选择在控制台显示额外信息
  if (process.env.NODE_ENV === 'development') {
    console.group('刷新历史记录');
    const history = getRefreshHistory();
    history.forEach((timestamp, index) => {
      console.log(`${index + 1}. ${new Date(timestamp).toLocaleTimeString()}`);
    });
    console.groupEnd();
  }
};

/**
 * 清除可能导致问题的缓存
 */
const clearTroublesomeCache = (): void => {
  try {
    // 清除认证状态
    localStorage.removeItem('auth-store');
    
    // 清除主题状态
    localStorage.removeItem('theme-storage');
    
    // 清除刷新历史
    clearRefreshHistory();
    resetRefreshCount();
    
    console.log('已清除可能导致刷新循环的缓存');
  } catch (error) {
    console.error('清除缓存时出错:', error);
  }
};

/**
 * 初始化调试工具
 */
export const initializeDebugTools = (): void => {
  // 在开发模式下添加到全局对象，方便调试
  if (process.env.NODE_ENV === 'development') {
    (window as any).debugTools = {
      getRefreshHistory,
      clearRefreshHistory,
      getRefreshCount,
      resetRefreshCount,
      detectRefreshLoop,
      handleRefreshLoop
    };
    
    console.log('调试工具已初始化，可在 window.debugTools 中访问');
  }
  
  // 记录页面加载
  recordRefresh();
};

// 默认导出
export default {
  detectRefreshLoop,
  getRefreshHistory,
  recordRefresh,
  clearRefreshHistory,
  getRefreshCount,
  incrementRefreshCount,
  resetRefreshCount,
  handleRefreshLoop,
  initializeDebugTools
};